package com.taobaostore.common;

import com.taobaostore.util.PropertiesUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPool {
	private static JedisPool pool;// jedis连接池
	private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getValue("redis.max.total", "20"));//最大连接数
	private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getValue("redis.max.idle", "20"));//最大空闲(Idle)数
	private static Integer minIdle = Integer.parseInt(PropertiesUtil.getValue("redis.min.idle", "20"));//最小空闲数
	private static Boolean testOnBorrw = Boolean.parseBoolean(PropertiesUtil.getValue("redis.test.borrow", "true"));//在(获取)borrow一个jedis实例的时候,是否要进行验证操作,如果赋值为true
	private static Boolean testReturn = Boolean.parseBoolean(PropertiesUtil.getValue("redis.test.return", "true"));//在(返回)ret*urn一个jedis实例的时候,是否要进行验证操作,则放回jedis的实例一定是可用的

	private static String redisIp = PropertiesUtil.getValue("redis.ip");
	private static Integer redisPort = Integer.valueOf(PropertiesUtil.getValue("redis.port"));

	// 初始化jedis连接池
	private static void initPool() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(maxTotal);
		config.setMaxIdle(maxIdle);
		config.setMinIdle(minIdle);
		config.setTestOnBorrow(testOnBorrw);
		config.setTestOnReturn(testReturn);

		config.setBlockWhenExhausted(true);// 连接耗尽的时候是否阻塞,false抛出异常,true为阻塞直到超时,默认为true

		pool = new JedisPool(config, redisIp, redisPort, 1000 * 2);
	}

	static {
		initPool();
	}

	/**
	 * 通过jedis连接池返回jedis
	 * @return
	 */
	public static Jedis getJedis() {
		return pool.getResource();
	}

	public static void returnResource(Jedis jedis) {
		pool.returnBrokenResource(jedis);
	}

	public static void returnBrokenResource(Jedis jedis) {
		pool.returnBrokenResource(jedis);
	}

	public static void main(String[] args) {
       Jedis jedis = pool.getResource();
       jedis.set("xzpkey", "xzpvalue");
       returnResource(jedis);
       
       pool.destroy();// 临时调用,销毁连接池中所有的连接
       System.out.println("program is end");
       
	}

}

